package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ConcurrentModificationException;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //1.校验老人是否已经入住，如果已经入住，则直接结束
        //根据身份证号和状态查询老人表
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1));
        if (elder != null) {
            return;
        }
        //2.更新床位状态为已入住
        //2.1 先根据床位id去查询床位实体对象
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        //2.2 再去更新床位状态
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.新增或者更新老人表
        elder = saveOrUpdateElder(dto, bed);

        //4.新增签约办理，插入合同表
        saveContract(dto,elder);

        //5.新增入住信息
        CheckIn checkIn = saveCheckIn(dto, elder);

        //6.新增入住配置信息
        saveCheckInConfig(checkIn,dto);
    }

    /**
     * 第四个抽取的方法，新增入住配置信息
     */
    private void saveCheckInConfig(CheckIn checkIn,CheckInApplyDto dto) {
        CheckInConfig checkInConfig=new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 第三个抽取的方法，新增入住信息
     * @param dto
     */
    private CheckIn saveCheckIn(CheckInApplyDto dto,Elder elder) {

        CheckIn checkIn=new CheckIn();

        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));//家属列表信息，json字符串
        checkIn.setStatus(0);

        this.save(checkIn);

        return checkIn;
    }

    /**
     * 第二个私有方法，新增签约办理
     * @param dto
     */
    private void saveContract(CheckInApplyDto dto,Elder elder) {
        //获取前端传递过来的合同相关对象
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract=new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);
        String contractNumber = "HT"+CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);//合同编号
        contract.setElderId(Integer.valueOf(elder.getId()+""));
        contract.setElderName(elder.getName());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);//开始时间
        contract.setEndDate(endDate);//结束时间
        boolean flag = startDate.isBefore(LocalDateTime.now());//判断开始时间是否在当前时间之前
        contract.setStatus(Long.valueOf(flag?1:0));//合同的状态，0:未生效, 1: 已生效, 2: 已过期, 3: 已失效

        //直接执行新增的sql
        contractMapper.insert(contract);
    }

    /**
     * 第一个私有方法，新增或者更新老人表
     * @param dto
     */
    private Elder saveOrUpdateElder(CheckInApplyDto dto, Bed bed) {
        //1.先获取老人信息，前端传递过来的
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder newElder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, newElder);
        newElder.setStatus(1);
        newElder.setBedId(bed.getId());
        newElder.setBedNumber(bed.getBedNumber());

        //1.判断老人信息是否已经存在
        Elder oldElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .ne(Elder::getStatus, 1));//状态不等于1
        if (oldElder != null){
            //更新
            elderMapper.updateById(newElder);
        }else{
            //新增
            elderMapper.insert(newElder);
        }
        return newElder;
    }
}